package com.example.demo.controller;
/*
 * 李洲 2020030654A1213
 * 2024.05.24
 */
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/headers")
public class HeaderController {

    // 处理带有单个请求头的GET请求
    @GetMapping("/single")
    public String getSingleHeader(@RequestHeader("User-Agent") String userAgent) {
        return "User-Agent: " + userAgent;
    }

    // 处理带有多个请求头的GET请求
    @GetMapping("/multiple")
    public String getMultipleHeaders(@RequestHeader("User-Agent") String userAgent,
                                     @RequestHeader("Accept-Language") String acceptLanguage) {
        return "User-Agent: " + userAgent + ", Accept-Language: " + acceptLanguage;
    }

    // 处理带有默认值的请求头的GET请求
    @GetMapping("/default")
    public String getHeaderWithDefault(@RequestHeader(value = "X-Custom-Header", defaultValue = "Default-Value") String customHeader) {
        return "X-Custom-Header: " + customHeader;
    }

    // 处理可选的请求头的GET请求
    @GetMapping("/optional")
    public String getOptionalHeader(@RequestHeader(value = "X-Optional-Header", required = false) String optionalHeader) {
        if (optionalHeader == null) {
            return "X-Optional-Header is not provided";
        }
        return "X-Optional-Header: " + optionalHeader;
    }

    // 处理带有所有请求头的GET请求
    @GetMapping("/all")
    public String getAllHeaders(@RequestHeader Map<String, String> headers) {
        StringBuilder sb = new StringBuilder();
        headers.forEach((key, value) -> sb.append(key).append(": ").append(value).append("\n"));
        return sb.toString();
    }
}
